package com.lemon.common.accessory.domain;

import com.lemon.common.config.UploadConfig;
import com.lemon.common.util.SpringUtils;
import lombok.Data;
import org.apache.commons.lang3.RandomStringUtils;
import org.apache.commons.lang3.time.FastDateFormat;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.multipart.MultipartFile;
import tk.mybatis.mapper.annotation.KeySql;

import javax.persistence.Column;
import javax.persistence.Id;
import javax.persistence.Table;
import javax.persistence.Transient;
import java.util.Date;

/**
 * 附件
 *
 * @author ymh
 * @date 2019-04-06 13:51
 */
@Data
@Table(name="sys_accessory")
public class Accessory {

    @Transient
    private UploadConfig uploadConfig = (UploadConfig) SpringUtils.getBean("uploadConfig");

    @Id
    @KeySql(useGeneratedKeys = true)
    private Long id;

    // 文件名
    private String name;

    // 原始文件名
    @Column(name = "orig_name")
    private String origName;

    // 文件大小
    private Long size;

    // 后缀名
    private String suffix;

    // 文件相对存放路径
    private String path;

    // 文件存放绝对
    @Transient
    private String absolutePath;

    // 创建时间
    private Long created;

    // 修改时间
    private Long updated;

    public Accessory() {

    }

    public Accessory(MultipartFile file) {
        String origName = file.getOriginalFilename();
        long size = file.getSize();
        String suffix = origName.substring(origName.lastIndexOf('.') + 1);
        String name = RandomStringUtils.randomAlphanumeric(20) + "." + suffix;
        String dir = uploadConfig.getPath();
        String relaPath = uploadConfig.getRelaPath(name);

        this.origName = origName;
        this.size = size;
        this.suffix = suffix;
        this.name = name;
        this.path = relaPath;
        this.absolutePath = dir + relaPath;
    }
}
